package com.emmy.walnut.presenter;

import android.os.Handler;
import android.os.Message;

import com.emmy.walnut.app.AppDatabase;
import com.emmy.walnut.constant.AppConstant;
import com.emmy.walnut.model.Record;
import com.emmy.walnut.presenter.iface.ExportPIface;
import com.emmy.walnut.util.TimeStampUtil;
import com.emmy.walnut.view.iface.ExportIface;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName ExportPresenter
 * @Description TODO
 * @Author zhouxuan
 * @Date 2020/02/19 10:04
 * @Version 1.0
 */
public class ExportPresenter implements ExportPIface {

    private ExportIface exportIface;

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what){
                case AppConstant.EXPORT_RECORD:
                    exportIface.exportFile((String)msg.obj);
                    break;
            }
            return false;
        }
    });

    public ExportPresenter(ExportIface exportIface){
        this.exportIface = exportIface;
    }

    @Override
    public void exportData(final int[] indexes, final long startTime, final long endTime, final boolean isOrderByLabel) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String FULL_PATH_NAME = AppConstant.APPLICATION_CONTEXT.getFilesDir().getAbsolutePath()+
                        "/report/";
                String FILE_NAME = TimeStampUtil.getYearMonthDayFormat(startTime)+"-"
                        + TimeStampUtil.getYearMonthDayFormat(endTime)+".csv";
                ArrayList<String> selectedLabels = new ArrayList<>();
                for (int index: indexes){
                    selectedLabels.add(AppConstant.activities.get(index).getLabelName());
                }
                List<Record> records;
                File file = new File(FULL_PATH_NAME+FILE_NAME);
                File folder = file.getParentFile();
                if (!folder.exists()){
                    folder.mkdirs();
                }
                if (file.exists()){
                    file.delete();
                }
                if (!isOrderByLabel){
                    records = AppDatabase.getInstance().recordDao().getRecordWithPeriodAndLabelsOrderByDate(
                            AppConstant.username, selectedLabels, startTime, endTime);
                    try{
                        file.createNewFile();
                        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file, true));
                        bufferedWriter.write("日期,类别,时长");
                        bufferedWriter.newLine();
                        for (Record record: records){
                            bufferedWriter.write(TimeStampUtil.getYearMonthDayFormat(record.getStartTimestamp())+
                                    ","+record.getLabelName()+","+
                                    TimeStampUtil.getFormatTime((int)(record.getEndTimestamp()-record.getStartTimestamp())));
                            bufferedWriter.newLine();
                        }
                        bufferedWriter.flush();
                        bufferedWriter.close();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }else{
                    records = AppDatabase.getInstance().recordDao().getRecordWithPeriodAndLabelsOrderByLabel(
                            AppConstant.username, selectedLabels, startTime, endTime);
                    try{
                        file.createNewFile();
                        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file, true));
                        bufferedWriter.write("类别,日期,时长");
                        bufferedWriter.newLine();
                        for (Record record: records){
                            bufferedWriter.write(record.getLabelName()+
                                    ","+ TimeStampUtil.getYearMonthDayFormat(record.getStartTimestamp())+","+
                                    TimeStampUtil.getFormatTime((int)(record.getEndTimestamp()-record.getStartTimestamp())));
                            bufferedWriter.newLine();
                        }
                        bufferedWriter.flush();
                        bufferedWriter.close();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                Message.obtain(handler, AppConstant.EXPORT_RECORD, FILE_NAME).sendToTarget();
            }
        }).start();
    }
}
